import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../l10n/app_localizations.dart';
import '../../models/serach_info_model.dart';
import '../../models/yh_info_model.dart';
import '../../services/yh_info_manger.dart';
import '../../services/number_utils.dart';
import '../../components/toast_utils.dart';
import '../../manger/network_utils.dart';

class ConfirmCouponView extends StatefulWidget {
  final ReListModel? selectedModel;
  final int pricenum;
  final String couponIds;
  final VoidCallback onShow;
  final void Function(double, String)? onDiscountChanged;
  const ConfirmCouponView({Key? key,this.selectedModel,this.pricenum = 1,required this.onShow,this.couponIds = "",this.onDiscountChanged}) : super(key: key);

  @override
  State<ConfirmCouponView> createState() => _ConfirmCouponViewState();
}

class _ConfirmCouponViewState extends State<ConfirmCouponView> {
  List<CouponListModel>? couponInfoModel;
  int isUseNum = 0; //通过updataCoupon条件判断有多少符合使用的优惠卷
  int expandId = -1; //兑换优惠卷的id
  int selectIndex = -1; //选择的优惠卷的索引
  TextEditingController controller = TextEditingController();
  ScrollController _scrollController = ScrollController();
  bool _isButtonEnabled = false;
  double discount = 0.0;
  List<CouponListModel>? filteredModels;
  List<CouponListModel>? unfilteredModels;
  @override
  void initState() {
    super.initState();
    updataCoupon();
  }

  @override
  bool _isManualSelection = false;

  void didUpdateWidget(covariant ConfirmCouponView oldWidget) {
    super.didUpdateWidget(oldWidget);

    if (!_isManualSelection && oldWidget.couponIds != widget.couponIds) {
      _updateSelectedIndex(widget.couponIds);
    }
    _isManualSelection = false;
  }

  void _updateSelectedIndex(String couponIds) {
    int index = filteredModels!.indexWhere((coupon) => coupon.spuCouponsId.toString() == couponIds);
    if (index != -1) {
      changeDiscount(index);      
    } else {
      setState(() {
        selectIndex = -1;
        discount = 0.0;
      });
      widget.onDiscountChanged?.call(0, "");
    }

  }

  void updataCoupon() async{

    if (widget.selectedModel == null) return;
    final result = await MyCouponManger().loadDiscountData(3,spuId: widget.selectedModel!.spuId,num: widget.pricenum);
    if (result.success && result.myCoupon != null) {
      filteredModels = result.myCoupon;
    }

    final result2 = await MyCouponManger().loadDiscountData(4,spuId: widget.selectedModel!.spuId,num: widget.pricenum);

    if (result2.success && result2.myCoupon != null) {
      unfilteredModels = result2.myCoupon;
    }
    
    setState(() {
      // isUseNum = 0;
      
      // 按面值从大到小排序
      // if (filteredModels != null) {
      //   filteredModels?.sort((a, b) => b.parvalue.compareTo(a.parvalue));
      //   setState(() {
      //     isUseNum = filteredModels?.length ?? 0;
      //   });
      // }

      isUseNum = filteredModels?.length ?? 0;
      // 合并列表
      couponInfoModel = null;
      couponInfoModel = [...?filteredModels, ...?unfilteredModels];

      // 查找是否有需要展开的优惠券
      if (expandId != -1) {
        var index = filteredModels?.indexWhere((coupon) => coupon.spuCouponsId == expandId) ?? -1;
        changeDiscount(index);
  
        if (index != -1) {
          expandId = -1;
          // 滚动到选中的优惠券位置
          WidgetsBinding.instance.addPostFrameCallback((_) {
            _scrollController.animateTo(
              index * 175.0, // 每个优惠券卡片宽度为160+15边距
              duration: Duration(milliseconds: 300),
              curve: Curves.easeInOut,
            );
          });
        }
      }
    });
  }

  void changeDiscount(int index){
    var coupon = couponInfoModel![index];
    var parvalue = coupon.parvalue;

    if (coupon.type == "1") {
      final totalAmount = double.parse(widget.selectedModel!.priceFee) * widget.pricenum;
      
      // 计算折扣金额
      double discountAmount = (1 - coupon.parvalue) * totalAmount;

      // 如果 coupon.max > 0，则进行 clamp；否则直接使用计算的折扣金额
      if (coupon.max > 0) {
        discountAmount = discountAmount.clamp(0, coupon.max);
      }

      // 四舍五入到小数点后两位
      parvalue = (discountAmount * 100).round() / 100;
    }
    
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {
        selectIndex = index;
        discount = parvalue;
      });
      widget.onDiscountChanged?.call(parvalue, coupon.spuCouponsId.toString());
    });
  }

  Future<void> _voucherCode(String text) async {
    ToastUtils.showLoadingToast(context);
    try {
      final response = await NetworkUtils.post(
        RequestCmd.voucherCode,
        body: {"voucherCode": text},
      );
      ToastUtils.dismissLoadingToast();
      final model = VoucherCodeModel.fromJson(response);
      if (model.code == 200) {
        ToastUtils.showCenterToast(context, model.msg);
        setState(() {
          expandId = model.data!.userSpuCouponsId;
          controller.text = "";
          _isButtonEnabled = false;
          updataCoupon();
        });
        
      } else {
        ToastUtils.showCenterToast(context, model.msg);
      }
    } catch (e) {
      ToastUtils.dismissLoadingToast();
      print(e);
    }
  }


  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(top: 15, left: 15, right: 15),
      decoration: BoxDecoration(
        color: Color(0xFFEAEAFF),
        borderRadius: BorderRadius.circular(15),
      ),
      child: Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              _buildNumberLabel('2'),
              SizedBox(width: 8),
              _buildTitleLabel(AppLocalizations.of(context)!.useDiscounts),
            ],
          ),
          _buildMainView(),
        ],
      ),
    );
  }

  Widget _buildNumberLabel(String number) {
    return Container(
      width: 18,
      height: 18,
      margin: const EdgeInsets.only(left: 10, top: 10,bottom: 10),
      decoration: BoxDecoration(
        color: Color(0xFF5D5FEE),
        shape: BoxShape.circle,
      ),
      child: Center(
        child: Text(
          number,
          style: TextStyle(color: Colors.white, fontSize: 13),
        ),
      ),
    );
  }

  Widget _buildTitleLabel(String title) {
    return Padding(
      padding: const EdgeInsets.only(top: 0),
      child: Text(
        title,
        style: TextStyle(fontSize: 14, color: Colors.black),
      ),
    );
  }

  Widget _buildMainView() {
    return Container(
      constraints: BoxConstraints(minHeight: 117),
      decoration: BoxDecoration(
        color: Color(0xFFFFFFFF),
        borderRadius: BorderRadius.circular(15),
      ),
      child: couponInfoModel == null || couponInfoModel!.isEmpty
          ? Column(
              children: [
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        AppLocalizations.of(context)!.coupon,
                        style: TextStyle(
                          color: Color(0xFF000000),
                          fontSize: 14,
                        ),
                      ),
                        GestureDetector(
                            onTap: () {
                              // 处理点击事件
                              widget.onShow();
                            },
                            child: Text(
                              '${AppLocalizations.of(context)!.noAvailable} >',
                              style: TextStyle(
                                color: Color(0xFFACACAC),
                                fontSize: 14,
                              ),
                            ),
                          ),
                    ],
                  ),
                ),
                _couponTextField()
              ],
            )
          : Column(
              children: [
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        AppLocalizations.of(context)!.coupon,
                        style: TextStyle(
                          color: Color(0xFF000000),
                          fontSize: 14,
                        ),
                      ),
                      isUseNum > 0
                          ? selectIndex != -1
                              ? Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    GestureDetector(
                                      onTap: () {
                                        widget.onShow();
                                      },
                                      child: Text(
                                        '-${couponInfoModel![0].symbol}$discount >',
                                        style: TextStyle(
                                          color: Color(0xFFF61F03),
                                          fontSize: 15,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                    ),
                                    SizedBox(width: 4),
                                    // Icon(Icons.arrow_forward_ios, size: 14, color: Color(0xFFF61F03)),
                                  ],
                                )
                              : Container(
                                  padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                  decoration: BoxDecoration(
                                    color: Color(0xFFF61F03),
                                    borderRadius: BorderRadius.circular(10),
                                  ),
                                  child: Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      GestureDetector(
                                        onTap: () {
                                          widget.onShow();
                                        },
                                        child: Text(
                                          '$isUseNum ${AppLocalizations.of(context)!.available} >',
                                          style: TextStyle(
                                            color: Colors.white,
                                            fontSize: 14,
                                          ),
                                        ),
                                      ),
                                      SizedBox(width: 4),
                                      // Icon(Icons.arrow_forward_ios, size: 14, color: Colors.white),
                                    ],
                                  ),
                                )
                          : Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                GestureDetector(
                                  onTap: () {
                                    widget.onShow();
                                  },
                                  child: Text(
                                    '${AppLocalizations.of(context)!.noAvailable} >',
                                    style: TextStyle(
                                      color: Color(0xFFACACAC),
                                      fontSize: 14,
                                    ),
                                  ),
                                ),
                                SizedBox(width: 4),
                                // Icon(Icons.arrow_forward_ios, size: 14, color: Color(0xFFACACAC)),
                              ],
                            ),
                            
                    ],
                  ),
                ),
                _listItemView(),
                _couponTextField()
              ],
            ),
    );
  }

  Widget _couponTextField() {
    return Padding(
      padding: EdgeInsets.only(top: 1, bottom: 15, left: 15, right: 15),
      child: Row(
        children: [
          Expanded(
            child: Container(
              height: 38,
              decoration: BoxDecoration(
                border: Border.all(color: Color(0xFFE6E6E6), width: 1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: TextField(
                controller: controller,
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.symmetric(horizontal: 10, vertical: 11),
                  hintText: AppLocalizations.of(context)!.enterCouponCode,
                  hintStyle: TextStyle(color: Color(0xFFACACAC), fontSize: 14),
                  border: InputBorder.none,
                ),
                style: TextStyle(color: Color(0xFF000000), fontSize: 14),
                keyboardType: TextInputType.text,
                inputFormatters: [
                  FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9]')),
                ],
                onChanged: (value) {
                  setState(() {
                    _isButtonEnabled = value.length >= 6;
                  });
                },
              ),
            ),
          ),
          SizedBox(width: 10),
    Container(
      width: 80,
      height: 34,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(17),
        gradient: _isButtonEnabled 
            ? LinearGradient(
                colors: [Color(0xFF8A9CFF), Color(0xFF5F60EF)],
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
              )
            : null,
        color: _isButtonEnabled ? null : Color(0xFFc2c3ff),
      ),
      child: TextButton(
        onPressed: _isButtonEnabled ? () => _voucherCode(controller.text) : null,
        style: TextButton.styleFrom(
          backgroundColor: Colors.transparent,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(17),
          ),
        ),
        child: Text(
          AppLocalizations.of(context)!.redeem,
          style: TextStyle(
            color: Colors.white,
            fontSize: 14,
          ),
          overflow: TextOverflow.ellipsis,  // 防止英文也换行
        ),
      ),
    )

        ],
      ),
    );
  }

  Widget _listItemView() {
    return SizedBox(
      height: 135,
      child: ListView.builder(
        controller: _scrollController,
        scrollDirection: Axis.horizontal,
        itemCount: couponInfoModel?.length ?? 0,
        itemBuilder: (context, index) {
          final coupon = couponInfoModel![index];
          // final isUse = double.parse(widget.selectedModel!.priceFee) * widget.pricenum > coupon.cill;
          final isUse = isUseNum > index;
          return Container(
            width: 160,
            margin: EdgeInsets.only(left: 15, right: index == couponInfoModel!.length - 1 ? 15 : 0),
            child: couponListItem(
              coupon: coupon,
              isUse: isUse,
              isSelected: index == selectIndex,
              onTap: () {
                _isManualSelection = true;
                setState(() {
                  if (selectIndex == index) {
                    selectIndex = -1;
                    widget.onDiscountChanged?.call(0, "");
                    setState(() {
                      discount = 0.0;
                    });
                  } else {
                    changeDiscount(index);
                  }
                });
              },
            ),
          );
        },
      ),
    );
  }

  Widget couponListItem({
    required CouponListModel coupon,
    required bool isUse,
    required bool isSelected,
    required VoidCallback onTap,
  }) {
    final bgColor = isUse ? Color(0xFFF3F3FF) : Color(0xFFF1F1F1);
    final textColor = isUse ? Color(0xFF5D5FEE) : Color(0xFF999999);
    
    return GestureDetector(
      onTap: isUse ? onTap : null,
      child: Column(
        children: [
          Container(
            height: 110,
            decoration: BoxDecoration(
              color: bgColor,
              borderRadius: BorderRadius.circular(12),
            ),
            child: Stack(
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: EdgeInsets.only(left: 10, top: 10),
                      child: Text(
                        coupon.type == "1" ? NumberUtils.formatDecimalValue(coupon.parvalue * 10)  : '${coupon.symbol} ${coupon.parvalue}',
                        style: TextStyle(
                          color: textColor,
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    SizedBox(height: 2),
                    Padding(
                      padding: EdgeInsets.only(left: 10),
                      child: Text(
                        coupon.infor,
                        style: TextStyle(
                          color: textColor,
                          fontSize: 11,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.only(top: 4, bottom: 2),
                      height: 10,
                      decoration: const BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage('assets/images/下载11.png'),
                          fit: BoxFit.fitWidth,
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 10),
                      child: Text(
                        coupon.effectiveTime,
                        style: TextStyle(
                          color: textColor,
                          fontSize: 11,
                        ),
                      ),
                    ),
                    SizedBox(height: 3),
                    Padding(
                      padding: EdgeInsets.only(left: 10),
                      child: Text(
                        coupon.description,
                        style: TextStyle(
                          color: Color(0xFF666666),
                          fontSize: 11,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
                if (isUse)
                  Positioned(
                    right: 10,
                    top: 10,
                    child: Image.asset(
                      isSelected ? 'assets/images/login_select.png' : 'assets/images/login_unselect2.png',
                      width: 20,
                      height: 20,
                    ),
                  ),
              ],
            ),
          ),
          if (!isUse)
            Padding(
              padding: EdgeInsets.only(top: 5),
              child: Row(
                children: [
                  Image.asset('assets/images/下载1.png', width: 14, height: 14),
                  SizedBox(width: 4),
                  Text(
                    AppLocalizations.of(context)!.noMatchingProducts,
                    style: TextStyle(
                      color: Color(0xFFFF0000),
                      fontSize: 11,
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 3)
        ],
      ),
    );
  }
}